from functools import wraps
from flask import g
from flask import session, redirect, url_for
from models import db, User, Host, Order
from utils import PermissionStr, PermissionBinary


def login_required(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        username = session.get('username')
        user = User.get_or_none(name=username)
        if None == user:
            return redirect(url_for('login'))
        g.user = user
        result = func(*args, **kwargs)
        return result

    return wrapper


def permission_str_required(permission):
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            print(f'decorated_function ssssssssssss')
            if not PermissionStr.can_do_permissions(permission):
                return {'status': 'fail', 'message': '没有权限'}
            return f(*args, **kwargs)

        return decorated_function

    return decorator


def permission_binary_required(permission):
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            if not PermissionBinary.can_do_permissions(permission):
                return {'status': 'fail', 'message': '没有权限'}
            return f(*args, **kwargs)

        return decorated_function

    return decorator
